#include <utility>
#include "SegTreeForScanLine.h"
#define lson (x << 1)
#define rson (x << 1 | 1)

using namespace std;
void SegTreeForScanLine::build(int l,int r,int x) {
    //测试用
    //cout<<l<<' '<<r<<endl;
    seg[x].l = l, seg[x].r = r;
    seg[x].len = 0;
    seg[x].sum = 0;
    if(l == r)
        return;
    int mid = (l + r) >> 1;
    build(l, mid, lson);
    build(mid+1, r , rson);
}
void SegTreeForScanLine::pushUp(int x) {
    int l = seg[x].l, r = seg[x].r;
    if(seg[x].sum) //如果被完全覆盖了已经
        seg[x].len = point[r + 1] - point[l]; //直接改为改线段长度
    else
        seg[x].len = seg[lson].len + seg[rson].len; //根据儿子信息修改
}
void SegTreeForScanLine::add(int x,long long L,long long R,int num) {
    int l = seg[x].l, r = seg[x].r;

    if(point[r + 1] <= L || R <= point[l])
        return;
    //这里表示如果覆盖
    if(L <= point[l] && point[r + 1] <= R) {
        seg[x].sum += num;
        pushUp(x);
        return;
    }
    //不覆盖就继续递归
    add(lson, L, R, num);
    add(rson, L, R, num);
    pushUp(x);
}
SegTreeForScanLine::SegTreeForScanLine(vector<int> p,int size) {
    point = move(p); //move可以减少资源的使用
    this->size = size;
    seg.resize(size * 4);
    build(1, size - 1, 1);
}
